<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-07-06 16:22:11
 * @Description: 所有售后退货退款的
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-07-06 17:36:40
 * @FilePath: /qingshanERP/app/Console/Commands/Test/PddAfter.php
 */

namespace App\Console\Commands\Test;

use Storage;
use App\Exports\ExportDemo;
use Illuminate\Console\Command;

class PddAfter extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pdd-after';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '退货退款';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $title   = [
            ['订单号', '快递单号', '退货物流公司名称', '类型']
        ];
        $data = [];
        $start_time = strtotime(date('2021-06-01 00:00:00'));
        while ($start_time <= strtotime(date('2021-07-07 00:00:00'))) {
            $params['access_token'] = 'b716f2a4fb844c09a0a7f7bce6819ebcc7e1bef5';
            $params['timestamp'] = strval(time());
            $params['after_sales_status'] = 10;
            $params['after_sales_type'] = 1;
            // $params['order_sn'] = '210501-394634209920284';
            $params['start_updated_at'] = $start_time;
            $params['end_updated_at'] = $start_time + 30 * 60;
            $params['page_size'] = 100;
            $params['page'] = 1;
            $has_next = true;
            while ($has_next) {
                $tmp = $this->request('pdd.refund.list.increment.get', $params);
                if (isset($tmp['refund_increment_get_response'])) {
                    $has_next = $tmp['refund_increment_get_response']['total_count'] >= 100 ? true : false;
                    if ($has_next) {
                        $params['page'] = $params['page'] + 1;
                    }
                    if (is_array($tmp['refund_increment_get_response']['refund_list'])) {
                        $data = array_merge($data, $tmp['refund_increment_get_response']['refund_list']);
                        // dump(count($tmp['refund_increment_get_response']['refund_list']));
                    }
                }else {
                    dump(date('Y-m-d H:i:s', $params['start_updated_at']).' - '. date('Y-m-d H:i:s', $params['end_updated_at']));
                    dump($tmp);
                }
                // sleep(1);
            }
            $start_time = $start_time + 30 * 60;
        }
        dump(count($data));
        // dd(1);
        $excel = [];
        foreach ($data as $v) {
            if ($v['after_sales_type'] == '3') {
                $excel[] = ['订单号'=>$v['order_sn'], '快递单号'=> isset($v['tracking_number']) ? $v['tracking_number'] : '', '退货物流公司名称'=>isset($v['shipping_name']) ? $v['shipping_name'] : '','类型'=> $v['after_sales_type']];
            }
        }
        \Maatwebsite\Excel\Facades\Excel::store(new ExportDemo($title, $excel), '/export/鸿阔5月退货单-'.date('Y-m-d H-i-s').'.xlsx', 'local');
    }

    /**
     * @param $params
     *
     * @return string
     */
    private function signature($params)
    {
        ksort($params);
        $paramsStr = '';
        array_walk($params, function ($item, $key) use (&$paramsStr) {
            if ('@' != substr($item, 0, 1)) {
                $paramsStr .= sprintf('%s%s', $key, $item);
            }
        });
        $client_secret = '22767be297ebd9387601e3316b66f3484fcc8723';
        return strtoupper(md5(sprintf('%s%s%s', $client_secret, $paramsStr, $client_secret)));
    }

    /**
     * @param string $method
     * @param array  $params
     * @param string $data_type
     *
     * @return mixed
     */
    public function request($method, $params = [], $data_type = 'JSON')
    {
        $config = [
            'client_id'    => '5b6b64a5ea0d450d84995b0dfc55f9d2',
            'client_secret' => '22767be297ebd9387601e3316b66f3484fcc8723',
            'member_type'        => 'LOGISTICS', //用户角色 ：MERCHANT(商家授权),H5(移动端),多多进宝推手(JINBAO),快团团团长(KTT),拼多多电子面单用户(LOGISTICS)
            'redirect_uri'       => 'https://qingshanerp.shanmuzhi.com/pddcallback',
        ];
        $params = $this->paramsHandle($params);
        $params['client_id'] = '5b6b64a5ea0d450d84995b0dfc55f9d2';
        $params['sign_method'] = 'md5';
        $params['type'] = $method;
        $params['data_type'] = $data_type;
        $params['timestamp'] = strval(time());
        $params['sign'] = $this->signature($params);
        // dump($params);
        // https://gw-api.pinduoduo.com/api/router?type=pdd.pop.auth.token.create&data_type=JSON&client_id=5b6b64a5ea0d450d84995b0dfc55f9d2&code=43f9d305fda94cd3872855fd67ab3cf99193eb2c&timestamp=1624848369&sign=B024CCA7179AF0BDFF8E229002BC06DE
        // return $params;
        $url = 'https://gw-api.pinduoduo.com/api/router';
        $res = $this->postCurl($url, $params);
        return $res;
    }
    // 请求接口用的CURL功能
    public function postCurl($url, $body, $type = "POST", $json = 0)
    {
        $header = array();
        //1.创建一个curl资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url); //设置url
        //1)设置请求头
        if ($json) {
            array_push($header, 'Content-Type:application/json');
        } else {
            array_push($header, 'Content-Type:application/x-www-form-urlencoded;charset=utf-8');
        }
        //设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时限制防止死循环
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算

        //3)设置提交方式
        switch ($type) {
            case "GET":
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true);
                break;
            case "PUT": //使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请 求。这对于执行"DELETE" 或者其他更隐蔽的HTT
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }

        //2)设备请求体
        if (count($body) > 0 && $type == 'POST') {
            // $body = $json ? json_encode($body) : $body;
            $postFields = http_build_query($body);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); //全部数据使用HTTP协议中的"POST"操作来发送。
        }

        //3.抓取URL并把它传递给浏览器
        $res = curl_exec($ch);
        $result = json_decode($res, true);
        //4.关闭curl资源，并且释放系统资源
        curl_close($ch);
        if (empty($result)) {
            return $res;
        } else {
            return $result;
        }
    }

    /**
     * @param array $params
     *
     * @return array
     */
    protected function paramsHandle(array $params)
    {
        array_walk($params, function (&$item) {
            if (is_array($item)) {
                $item = json_encode($item);
            }
            if (is_bool($item)) {
                $item = ['false', 'true'][intval($item)];
            }
        });

        return $params;
    }
}
